package com.samphanie.auiu.route

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.samphanie.auiu.biz.account.AccountManager
import com.samphanie.auiu.library.utils.MainHandler
import java.lang.RuntimeException

/**
 * @author ZSY
 */
@Interceptor(name = "biz_interceptor", priority = 9)
class BizInterceptor : IInterceptor {

    private var context: Context? = null

    override fun init(context: Context?) {
        this.context = context
    }

    override fun process(postcard: Postcard?, callback: InterceptorCallback?) {
        val flag = postcard!!.extra

        if ((flag and (RouteFlag.FLAG_LOGIN) != 0)) {
            callback!!.onInterrupt(RuntimeException("need login"))
            loginIntercept(postcard, callback)
        }
//        else if ((flag and (RouteFlag.FLAG_AUTHENTICATION) != 0)) {
//            callback!!.onInterrupt(RuntimeException("need authentication"))
//            showToast("请先实名认证")
//        } else if ((flag and (RouteFlag.FLAG_VIP) != 0)) {
//            callback!!.onInterrupt(RuntimeException("need vip"))
//            showToast("请先成为会员")
//        }
        else {
            callback!!.onContinue(postcard)
        }
    }

    private fun loginIntercept(postcard: Postcard?, callback: InterceptorCallback?) {
        MainHandler.post {
            showToast("请先登录")
            if (AccountManager.isLogin()) {
                callback?.onContinue(postcard)
            } else {
                AccountManager.login(context) {
                    callback?.onContinue(postcard)
                }
            }
        }
//        Handler(Looper.myLooper()!!).post {
//            showToast("请先登录")
//            ARouter.getInstance().build("/account/login").navigation()
//        }

    }

    private fun showToast(message: String) {
        Handler(Looper.getMainLooper()).post {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        }
    }
}